<?php

namespace App\Console\Commands;

use App\RunGameSeason;
use App\User;
use Illuminate\Console\Command;
use App\RunGameRank as Rank;
use DB;

class RunGameRank extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rungame:rank';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '游戏排行榜虚拟排行';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //检查脚本是否在执行
        $this->check();
        $time = time();
        //提取虚假用户
        $user_ids = User::where('sign', User::SIGN_NO)->pluck('c_id')->toArray();
        shuffle($user_ids);
        $user_ids = array_slice($user_ids, 0, 20);
        $insert = [];
        foreach ($user_ids as $user_id) {
            //分数
            $integral = mt_rand(10,22);
            //赛季
            $thisSeason = intval(RunGameSeason::ThisSeason());
            $rank = Rank::select('id', 'integral')->where('user_id', $user_id)->where('season_id', $thisSeason)->first();
            if ($rank) {
                DB::table('run_game_rank')->where('id', $rank->id)->update([
                    'integral' => $rank->integral + $integral,
                    'updated_at' => $time,
                ]);
            } else {
                $insert[] = [
                    'user_id' => $user_id,
                    'integral' => $integral,
                    'season_id' => $thisSeason,
                    'created_at' => $time,
                    'updated_at' => $time,
                ];
            }
        }
        if (count($insert)) {
            DB::table('run_game_rank')->insert($insert);
        }
        exit('ok');
    }

    public function check()
    {
        $file = 'rungame_game.lock';
        $lock_file = storage_path($file);
        if (!flock($this->fp = fopen($lock_file, 'w'), LOCK_NB | LOCK_EX)) {
            //无法取得锁就退出
            logger($this->description . ' 脚本尝试重复启动');
            die('cannot get lock，already running?');
        }
        register_shutdown_function('unlink', $lock_file);
    }
}
